import { createSlice } from "@reduxjs/toolkit";

const initialState = [
  { id: "1", title: "first post！", content: "hello!" },
  { id: "2", title: "second post!", content: "more text" },
];

const postsSlice = createSlice({
  name: "posts",
  initialState,
  reducers: {
    postAdded(state, action) {
      state.push(action.payload);
    },
    postUpdated(state, action) {
      const { id, title, content } = action.payload;
      const findPost = state.find((post) => post.id === id);
      if (findPost) {
        findPost.content = content;
        findPost.title = title;
      }
    },
    postDeleted(state, action) {
      const { id } = action.payload;
      const postIndex = state.findIndex((post) => post.id === id);
      if (postIndex > -1) {
        state.splice(postIndex, 1);
      }
    },
  },
});
export const { postAdded, postUpdated,postDeleted } = postsSlice.actions;
export default postsSlice.reducer;
